const {ccclass, property} = cc._decorator;
import Q1Util from "./Q1Util";
import {MATRIX_SIZE, COLORS} from "./Q1Util";


@ccclass
export default class Q1 extends cc.Component {

    @property(cc.EditBox)
    editBoxX: cc.EditBox = null;

    @property(cc.EditBox)
    editBoxY: cc.EditBox = null;

    @property(cc.Node)
    blockMatrixNode: cc.Node = null;

    @property(cc.Prefab)
    blockPrefab: cc.Prefab = null;

    @property(cc.Node)
    blockContainer: cc.Node = null;

    private blockNodes: cc.Node[][] = [];
    private q1Util: Q1Util = null;

    onLoad () {
        this.q1Util = new Q1Util();
        this.blockMatrixNode.active = false;
    }

    // 生成按钮被点击
    generateClick(): void {
        let adjustX: number = 0;
        let adjustY: number = 0;
        
        let XStr: string = this.editBoxX.string;
        let YStr: string = this.editBoxY.string;
        if (XStr === "") {
            adjustX = 0;
        } else {
            adjustX = parseInt(XStr);
        }

        if (YStr === "") {
            adjustY = 0;
        } else {
            adjustY = parseInt(YStr);
        }

        if (adjustX < 0) {
            adjustX = 0;
        } else if (adjustX > 80) {
            adjustX = 80;
        }

        if (adjustY < 0) {
            adjustY = 0;
        } else if (adjustY > 80) {
            adjustY = 80;
        }

        this.q1Util.setAdjust(adjustX, adjustY);

        let matrix: number[][] = this.q1Util.generateColorIdxs();
        
        this.displayMatrix(matrix);
        
        this.blockMatrixNode.active = true;
    }

    // 根据生成的矩阵显示实际的内容
    displayMatrix(matrix: number[][]): void {
        if (this.blockNodes.length > 0) {
            for (let  m= 0; m < MATRIX_SIZE; m++) {
                for (let n = 0; n < MATRIX_SIZE; n++) {
                    this.blockNodes[m][n].color = COLORS[matrix[m][n]];
                }
            }
        } else {
            for (let  m= 0; m < MATRIX_SIZE; m++) {
                this.blockNodes[m] = [];
                for (let n = 0; n < MATRIX_SIZE; n++) {
                    let node = cc.instantiate(this.blockPrefab);
                    node.color = COLORS[matrix[m][n]];
                    this.blockContainer.addChild(node);
                    this.blockNodes[m][n] = node;
                }
            }
        }
    }
}
